import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, ObservableLike } from 'rxjs';
import { map } from 'rxjs/operators';
import * as gc from 'src/app/global/globalconst';


export class Config{
  iid:number;
  switchername:string;
  value:number;
  desc:string;
}

export class WebAuthorizeResult{
  access_token:string;
  expires_in:number;
  refresh_token:string;
  openid:string;
  scope:string;

  toString():string{
    return 'access_token:' + this.access_token + ',expires_in:' + this.expires_in + ',refresh_token:' + this.refresh_token + ',openid:' + this.openid + ',scope:' + this.scope;
  }
}

export class Result{
  code:number;msg:string;data:any;
}

const contextPath:string = gc.server;
const pre:string="/switch";

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  
  url = {
    'selectBySwitcherName':gc.server + pre + '/selectBySwitcherName',
    'closePushProcess':contextPath + pre + '/closePushProcess',
    'openPushProcess':contextPath + pre + '/openPushProcess',
    'getOpenidByOAuth':contextPath + pre + '/oao',
    'getAccessToken':'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxa62e3fc6d5361bc9&secret=5da509555b914f7d257d2f2c47a45b72&code=CODE&grant_type=authorization_code'

  }

  switchers = {
    'PUSH_PROCESS':'刷卡推送',
    'PUSH_FINISHED_PRODUCT':'成品发货推送'
  }
  
  constructor(
    private http:HttpClient
  ) { }

  closePushProcess():Observable<Boolean>{
    return this.http.get(this.url.closePushProcess).pipe(
      map((res:number)=>{
        return res===1?true:false;
      })
    )
  }


  openPushProcess():Observable<Boolean>{
    return this.http.get(this.url.openPushProcess).pipe(
      map((res:number)=>{
        return res===1?true:false;
      })
    )
  }

  selectBySwitcherName(switcherName:String):Observable<Config>{
    const url = this.url.selectBySwitcherName + '/' + switcherName;
    return this.http.get<Config>(url);
  }

  getOpenidByOAuth(code:string):Observable<Result>{
    const url = this.url.getOpenidByOAuth + '/' + code;
    console.log('请求openid 的请求是：' + url);
    
    return this.http.get<Result>(url);
  }


  getAccessToken(code:string):Observable<WebAuthorizeResult>{
    console.log('服务中的 getAccessToken 替换参数之前的URL:');
    console.log(this.url.getAccessToken);
    const url:string = this.url.getAccessToken.replace('CODE',code);
    console.log('替换之后：');
    console.log(url);

    let header:HttpHeaders = new HttpHeaders();
    // header.append('Access-Control-Allow-Methods','POST,GET');
    // header.append('Access-Control-Allow-Credentials','true');
    // header.append('Access-Control-Allow-Headers','Origin,Content-Type,Accept,token,X-Requested-With');
    // return this.http.get<WebAuthorizeResult>(url,{ headers:header });
    return this.http.get<WebAuthorizeResult>(url);
  }

}
